package danny.hoi.controller;


import danny.hoi.pojo.Result;
import danny.hoi.utils.FastDFSClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/upload")
@RestController
public class PicUploadController {

    /**
     * fast商品图片上传
     *
     * @param file
     * @return
     */
    @PostMapping
    public Result upload(MultipartFile[] file) {
        try {
            if (file != null && file.length > 0) {
                for (MultipartFile multipartFile : file) {
                    // 1.创建文件上传工具类
                    FastDFSClient fastDFSClient = new FastDFSClient("classpath:fastDFS/fastdfs.conf");
                    //2.得到上传文件的扩展名
                    String extName = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
                    //3.上传文件
                    String uploadFile = fastDFSClient.uploadFile(multipartFile.getBytes(), extName);
                    //4.回传上传的文件路径
                    return Result.ok(uploadFile);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail("上传失败了!");
    }


    /**
     * fast商品图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/kindUpload")
    public Map<String, Object> kindUpload(MultipartFile[] file) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (file != null && file.length > 0) {
                for (MultipartFile multipartFile : file) {
                    // 1.创建文件上传工具类
                    FastDFSClient fastDFSClient = new FastDFSClient("classpath:fastDFS/fastdfs.conf");
                    //2.得到上传文件的扩展名
                    String extName = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
                    //3.上传文件
                    String uploadFile = fastDFSClient.uploadFile(multipartFile.getBytes(), extName);
                    //4.回传上传的文件路径
                    map.put("error", 0);
                    map.put("url", uploadFile);
                    return map;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("url", "上传失败了");
        return map;
    }
}
